# 在所有其他导入之前应用兼容性补丁
import fix_secure_cookie

from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from datetime import datetime, time
import uvicorn
from pathlib import Path
from router.books import router as books_router
from router.bookshelf import router as bookshelf_router
from router.categories import router as categories_router
from router.users import router as users_router
from router.reading_positions import router as reading_positions_router
from router.user_ratings import router as user_ratings_router
from router.user_purchases import router as user_purchases_router
from router.user_search_history import router as user_search_history_router
from router.avatar import router as avatar_router
from db import db_connection


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理器"""

    # 在应用启动时创建数据库连接池
    await db_connection.create_pool()

    yield

    # 关闭数据库连接池
    await db_connection.close_pool()


# 创建FastAPI应用实例
app = FastAPI(
    title="BookStore API",
    description="图书管理系统后端API",
    version="1.0.0",
    lifespan=lifespan,
)


# 注册子路由
app.include_router(books_router, prefix="/api")
app.include_router(bookshelf_router, prefix="/api")
app.include_router(categories_router, prefix="/api")
app.include_router(users_router, prefix="/api")
app.include_router(reading_positions_router, prefix="/api")
app.include_router(user_ratings_router, prefix="/api")
app.include_router(user_purchases_router, prefix="/api")
app.include_router(user_search_history_router, prefix="/api")
app.include_router(avatar_router, prefix="/api")


# 根路由
@app.get("/")
async def root():
    return {
        "message": "BookStore API 后端已经启动",
        "documentation": "访问 /docs 查看API文档",
    }


# api介绍
@app.get("/api")
async def api_info():
    return {
        "接口介绍": "BookStore API",
    }


# 处理 favicon.ico 请求，返回空响应
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
    """返回空的 favicon 响应以避免 404 错误"""
    return Response(status_code=204)


if __name__ == "__main__":
    backend_dir = Path(__file__).parent
    uvicorn.run(
        "main:app",
        host="localhost",
        port=8080,
        reload=True,  # 添加热重载
        reload_dirs=[str(backend_dir)],  # 监控后端目录变化
    )
